load "$NCARG_ROOT/lib/ncarg/nclscripts/csm/gsn_code.ncl"
load "$NCARG_ROOT/lib/ncarg/nclscripts/csm/gsn_csm.ncl"
load "$NCARG_ROOT/lib/ncarg/nclscripts/csm/contributed.ncl"
load "$NCARG_ROOT/lib/ncarg/nclscripts/wrf/WRFUserARW.ncl"
load "$NCARG_ROOT/lib/ncarg/nclscripts/wrf/WRF_contributed.ncl"
load "$NCARG_ROOT/lib/ncarg/nclscripts/contrib/ut_string.ncl"
load "/public/users/wrf/Codes/WRF_scripts/utils/substring.ncl"
load "/public/users/wrf/Codes/WRF_scripts/utils/WRF_dyy_contributed.ncl"

; open csv file to generate the polygon
csvfile = "/public/users/wrf/Data/WuJiang_Map/wujiang_domaian_mask_d02.csv"
wrf_mask = readAsciiTable(csvfile,4,"float",1)
ij_masks = tointeger(wrf_mask(:,2:3))
dim_mask = dimsizes(ij_masks)

; open wrfout file to get the domain lat/lon information
wrfout_file = "/public/users/wrf/wrfout/2012111420/wrfout_d02_2012-11-14_12:00:00"
a = addfile(wrfout_file + ".nc", "r")
xlong = wrf_user_getvar(a, "XLONG", 0)
xlat  = wrf_user_getvar(a, "XLAT", 0)
rain_exp = wrf_user_getvar(a, "RAINNC", -1)
rain_con = wrf_user_getvar(a, "RAINC", -1)
rain_tot = rain_exp + rain_con
dim_rain = dimsizes(rain_tot)
printVarSummary(rain_tot)

xlong_crop = new(dim_mask(0), "float")
rain_crop = new((/dim_rain(0),dim_mask(0)/), "float")
do i = 0,dim_mask(0)-1,1
    xlong_crop(i) = xlong(ij_masks(i,1), ij_masks(i,0))
    rain_crop(:,i) = rain_tot(:,ij_masks(i,1), ij_masks(i,0))
end do
printVarSummary(rain_crop)
rain_crop_tot = dim_sum(rain_crop) / tofloat(dim_mask(0))
print(rain_crop_tot)
